package com.neuedu.jdbc;

import java.sql.*;

/**
 * @author 金山
 * 项目：jdbc
 * site: https://blog.fulfill.com.cn
 * 描述  入门
 * @data 2024/11/88:48
 */
public class JDBCTest {


    /**
     * 旧版本  8-
     * // Class.forName("com.mysql.jdbc.Driver");
     * @param args
     */
    public static void main(String[] args) {



        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //载入JDBC驱动程序：  //8.0+
            Class.forName("com.mysql.cj.jdbc.Driver");

            //建立数据库连接对象：
            // String url = "http://www.baidu.com:80/search";

            // String url = "jdbc:mysql//localhost:3306/test";
            String url = "jdbc:mysql://127.0.0.1:3306/test";
            String username = "root";
            String password = "root";
            con = DriverManager.getConnection(url,username,password);

            //创建Statement对象
            stmt = con.createStatement();

            /**
             * CRUD  增删改查
             * query   :  select
             * update   : insert  update   delete
             */
            String sql = " select count(1) c from emp ";
            rs = stmt.executeQuery(sql);


            //解析结果集
           if(rs.next()){  //进入到 if 中说明有数据

                //rs 现在指向的是数据 行
               // int count = rs.getInt(1);
               int count = rs.getInt("c");


               System.out.println("count = " + count);
           }


        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(con != null){
                try {
                    con.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

        }

    }

}
